import { DmActionType } from '../actions/dmAction'
import { singleClone, Type } from '@utils/Global'

let originQuestions = [], originAnswers = []
const dm_state = {
  list: [],
  show: true,
  value: '',
  dmType: 'common'
}
const DmState = (state = dm_state, action) => {
  let _state = singleClone(state)
  switch (action.type) {
    case DmActionType.get_system_dm:
      return Object.assign({}, state, {
        list: _state.list.concat([action.msg])
      })
    case DmActionType.init_dm:
      return Object.assign({}, state, {
        list: action.list
      })
    case DmActionType.insert_dm:
      const currentList = state.list.concat([action.item])
      return Object.assign({}, state, {
        list: currentList
      })
    case DmActionType.toggle_dm:
      return Object.assign({}, state, {
        show: action.show
      })
    case DmActionType.set_value:
      return Object.assign({}, state, {
        value: action.value
      })
    case DmActionType.toggle_dm_type:
      return Object.assign({}, state, {
        dmType: action.dmType
      })
    case DmActionType.get_dm_answer_msg:
      let cloneAnswerMsg = singleClone(action.payload.msg)
      _state.list.push(cloneAnswerMsg)
      return _state
    case DmActionType.get_dm_question_msg:
      let cloneQuestionMsg = singleClone(action.payload.msg)
      if (!action.payload.isRemoteSelf) {
        _state.list.push(cloneQuestionMsg)
      } else {
        let filter = _state.list.find(r => {
          return r.type === Type.COMMON_TYPE.COMMON_DM_QUESTION && r.data.uuid === cloneQuestionMsg.data.uuid
        })
        if (filter) {
          filter.data.question =  cloneQuestionMsg.data.question
          filter.data.question_id = cloneQuestionMsg.data.question.id
        }
      }
      return _state
    case DmActionType.get_dm_question_up_msg:
      let cloneQuestionUpMsg = singleClone(action.payload.msg)
      let filter = _state.list.find(r => {
        return r.type === Type.COMMON_TYPE.COMMON_DM_QUESTION
          && r.data.question.id === cloneQuestionUpMsg.data.question.id
      })
      if (filter) {
        filter.data.question = cloneQuestionUpMsg.data.question
      }
      return _state
    case DmActionType.do_self_like_dm_item:
      if (action.payload.msgType === 'question') {
        let selfUpFilter = _state.list.find(r => {
          return r.type === Type.COMMON_TYPE.COMMON_DM_QUESTION
            && r.data.question.id === action.payload.id
        })
        if (selfUpFilter) {
          selfUpFilter.data.question.up_num += 1
          selfUpFilter.data.question.like = true
        }
      }
      return _state
    default:
      return state
  }
}
DmState._default_state = dm_state
export default DmState
